package com.fengye.security.jwt.process;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 获取有权访问当前url的角色列表/权限列表
 * <p>
 * 不需要权限就返回空 - 如果返回空,不会向后执行继续判断
 */
@Component("jwtFilterInvocationSecurityMetadataSource")
@Slf4j
public class JwtFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

//    @Autowired
//    private SysPermissionRepository repository;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 加载数据库数据,查询出当前url应该拥有的权限.
     * <p>
     * 可以是角色集合,也可以是自定义的权限字符串.
     * <p>
     * 交由 JwtUrlAccessDecisionManager.decide 方法来确定能否访问.
     *
     * @param object request url
     * @return 可以访问当前url的权限集合.
     * @throws IllegalArgumentException {@link IllegalArgumentException}
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();

//        List<SysPermission> all = repository.findAll();
        // List<SystemUrlInfo> allUrls = systenUrlService.getAllSystemUrl();
        Set<String> perms = new HashSet<>();
//        for (SysPermission url : all) {
//            if (antPathMatcher.match(url.getUrlPath(), requestUrl)
//                    // && url.getRoles().size() > 0
//            ) {
//                // url.getRoles().stream().flatMap(u ->
//                //         url.getRoles().stream().map(SysRole::getName)
//                // ).forEach(roles::add);
//                perms.add(url.getPermString());
//
//            }
//        }
        if (antPathMatcher.match("/jwt/test", requestUrl)){
            perms.add("test");
        }
        String[] perm = perms.toArray(new String[0]);
        if (perm.length > 0) {
            log.info("该url = {},需要的权限为 {}", requestUrl, perm);
        } else {
            log.info("该url = {},不需要任何权限", requestUrl);
        }

        // 如果没有匹配，则默认全部可以访问
        return SecurityConfig.createList(perm);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        log.info("谁调用了com.fengye.security.jwt.process.JwtFilterInvocationSecurityMetadataSource#getAllConfigAttributes");
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }

}